package net.wanho.service.impl;

import lombok.SneakyThrows;
import net.wanho.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * Author：汤小洋
 * Date：2025-02-05 16:40
 * Description：<描述>
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${file.path}")
    private String localFilePath;

    @Value("${file.prefix}")
    private String localFilePrefix;

    @Value("${file.domain}")
    private String domain;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        String uploadDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
        File uploadPath = new File(localFilePath + File.separator + uploadDir + File.separator + filename);

        if(! uploadPath.getParentFile().exists()){
            uploadPath.getParentFile().mkdir();
        }

        file.transferTo(uploadPath);

        return domain + localFilePrefix + "/" + uploadDir + "/" + filename;
    }
}
